'use strict';

/**
 * @ngdoc service
 * @name jgappApp.MapService
 * @description
 * # MapService
 * Service in the jgappApp.
 */
angular.module('jgappApp')
    .service('MapService', function ($q, Util, $http) {
        // AngularJS will instantiate a singleton by calling "new" on this function
        var MapService = {}
        MapService.createInstance = function (opts, element) {
            // create map instance
            var map = new BMap.Map(element[0]);
            // init map, set central location and zoom level
            map.centerAndZoom(new BMap.Point(opts.center.longitude, opts.center.latitude), opts.zoom);
            if (opts.navCtrl) {
                // add navigation control
                map.addControl(new BMap.NavigationControl());
            }
            if (opts.scaleCtrl) {
                // add scale control
                map.addControl(new BMap.ScaleControl());
            }
            if (opts.overviewCtrl) {
                //add overview map control
                map.addControl(new BMap.OverviewMapControl());
            }
            if (opts.enableScrollWheelZoom) {
                //enable scroll wheel zoom
                map.enableScrollWheelZoom();
            }

            // set the city name
            // map.setCurrentCity(opts.city);
            return map;
        };

        var _createMarker = function (marker, pt) {
            var markerinstance;
            // if (marker.icon) {
            //     var icon = new BMap.Icon(marker.icon, new BMap.Size(marker.width, marker.height));
            //     markerinstance = BMap.Marker(pt, { icon: icon });
            //     markerinstance.enableDragging();
            //     return markerinstance
            // }
            markerinstance = new BMap.Marker(pt);
            return markerinstance

        };
        MapService.redrawMarkers = function (map, previousMarkers, opts) {
            // previousMarkers.forEach(function({ marker, listener }) {
            //     marker.removeEventListener('click', listener);
            //     map.removeOverlay(marker);
            // });
            // previousMarkers.length = 0;
            map.clearOverlays(previousMarkers);
            if (!opts.markers) {
                return;
            }
            opts.markers.forEach(function (marker) {
                var marker2 = _createMarker(marker, new BMap.Point(marker.longitude, marker.latitude));
                map.addOverlay(marker2);
                if (opts.enableDragging) {
                    marker2.enableDragging();
                }
                // var previousMarker = { marker: marker2, listener: null };
                // previousMarkers.push(previousMarker);

                // if (!marker.title && !marker.content) {
                //     return;
                // }
                // var msg = "<p>"+marker.title+"</p><p>"+marker.content+"</p>";
                // var infoWindow2 = new BMap.InfoWindow(msg, {
                //     enableMessage: !!marker.enableMessage
                // });
                // previousMarker.listener = function() {
                //     this.openInfoWindow(infoWindow2);
                // };
                // marker2.addEventListener('click', previousMarker.listener);

            });
        };

        MapService.setMarker = function (map, myValue, opts) {
            map.clearOverlays(); //清除地图上所有覆盖物
            var local = new BMap.LocalSearch(map, { //智能搜索
                onSearchComplete: function () {
                    var pp = local.getResults().getPoi(0).point; //获取第一个智能搜索的结果
                    map.centerAndZoom(pp, 18);
                    var marker = new BMap.Marker(pp)
                    map.addOverlay(marker); //添加标注
                    if (opts.enableDragging) {
                        marker.enableDragging();
                    }

                }
            });
            local.search(myValue);
        };
        // 根据经纬度获取当前地址
        MapService.getLocation = function (point) {
            var defer = $q.defer();
            var point = new BMap.Point(point.longitude, point.latitude);
            var geoc = new BMap.Geocoder();
            geoc.getLocation(point, function (rs) {
                var addComp = rs.address;
                defer.resolve(addComp)
            });
            return defer.promise;
        };
        MapService.getcurPositon = function () {
            var defer = $q.defer();
            // android定位与ios定位方法不同
            if (typeof baidu_location != "undefined") {
                baidu_location.getCurrentPosition(function (data) {
                    // MapService.transformPoint(data, MapService.getAk(), MapService.getMcode()).then(function(data) {
                    //         defer.resolve(data)
                    //     })
                    MapService.getLocation(data).then(function (address) {
                        data.address=address
                        defer.resolve(data)
                    })

                }, function (data) {
                    console.log(data);
                });
            } else if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function (data) {
                    MapService.transformPoint(data.coords, MapService.getAk(), MapService.getMcode()).then(function (data) {
                        MapService.getLocation(data).then(function (address) {
                            data.address=address
                            defer.resolve(data)
                        })
                    })
                    // defer.resolve(data.coords)
                }, function (data) {
                    console.log(data);
                }, { enableHighAccuracy: true });
            } else {
                var point = {
                    longitude: 115.863834,
                    latitude: 28.68003,
                    address: "测试地址"
                }
                defer.resolve(point)

            }
            return defer.promise;
        };
        MapService.transformPoint = function (param, ak, mcode) {
            var defer = $q.defer();
            var api = "http://api.map.baidu.com/geoconv/v1/?coords=" + param.longitude + "," + param.latitude + "&ak=" + ak + "&mcode=" + mcode;
            $http.get(api, { noloader: true })
                .success(function (data) {
                    var point = {};
                    if (data.status == 0) {
                        point.longitude = data.result[0].x
                        point.latitude = data.result[0].y
                        defer.resolve(point);
                    } else {
                        defer.reject("获取用户信息出错");
                        Util.Toast(data.message)
                    }
                }).error(function () {
                    // Util.Toast("无法连接到服务器")
                    defer.reject("获取用户信息出错");
                });
            return defer.promise;
        };
        MapService.getDistance = function (p1, p2) {
            /** 
             * 计算两点之间距离 
             * @param start 
             * @param end 
             * @return 米 
             */
            var lat1 = (Math.PI / 180) * p1.latitude;
            var lat2 = (Math.PI / 180) * p2.latitude;

            var lon1 = (Math.PI / 180) * p1.longitude;
            var lon2 = (Math.PI / 180) * p2.longitude;
            //地球半径  
            var R = 6371;

            //两点间距离 km，如果想要米的话，结果*1000就可以了  
            var d = Math.acos(Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1)) * R;
            d = parseInt(d * 1000, 10);
            console.log(d)
            return d
        };
        // 计算是否允许打卡
        MapService.permissionDistance = function (p1, p2, deviation) {
            var distance;
            distance = MapService.getDistance(p1, p2);
            return distance < deviation
        };
        MapService.getAk = function () {
            var ak;
            if (Util.getPlatform() == "android") {
                ak = "LvGLjO3Sb832PyNx2EfzovtglbSIR0Mm";
            } else if (Util.getPlatform() == "ios") {
                ak = "8W5P6KRFBF6NXs8GbsEnjPfcjcHS4n1b";
            }
            return ak
        };
        MapService.getMcode = function () {
            var mcode;
            if (Util.getPlatform() == "android") {
                mcode = "DB:2F:39:27:23:5B:38:10:A2:DC:58:AC:F8:0B:73:A0:CF:2C:CE:0F;com.jianguanoa.jgapp";
            } else if (Util.getPlatform() == "ios") {
                mcode = "com.jianguanoa.com";
            }
            return mcode
        };
        return MapService;
    });
